/*
 * @Description: 
 * @Author: 黎志恒
 * @LastEditors: 黄勇
 * @Date: 2019-03-23 10:42:33
 * @LastEditTime: 2020-03-24 14:07:41
 */

import axios from "axios";
import _this from "@/main.js";
import header from './header'
import user from './user'
import files from './files'
import app from './app'
import experience from './experience'

const reqAndUrl = Object.assign({},
    header,
    user,
    files,
    app,
    experience
);
class ApiService {
    getSessionData(sessionItem) {
        let sessionValue = sessionStorage.getItem(sessionItem);
        if (!sessionValue) {
            this.setSessionData(sessionItem, JSON.stringify({}));
        }
        sessionValue = sessionStorage.getItem(sessionItem);
        return JSON.parse(sessionValue);
    }
    setSessionData(sessionItem, sessionValue) {
        if (sessionValue instanceof Object) {
            return sessionStorage.setItem(sessionItem, JSON.stringify(sessionValue));
        }
        sessionStorage.setItem(sessionItem, sessionValue);
    }
    removeSessionData(sessionItem) {
        sessionStorage.removeItem(sessionItem);
    }
    getLocalData(localItem) {
        let localValue = localStorage.getItem(localItem);
        if (!localValue) {
            this.setLocalData(localItem, JSON.stringify({}));
        }
        localValue = localStorage.getItem(localItem);
        return JSON.parse(localValue);
    }
    setLocalData(localItem, localValue) {
        if (localValue instanceof Object) {
            return localStorage.setItem(localItem, JSON.stringify(localValue));
        }
        localStorage.setItem(localItem, localValue);
    }
    removeLocalData(localItem) {
        localStorage.removeItem(localItem);
    }
}

//拦截axios请求
axios.interceptors.request.use(
    function (config) {
        //axios不允许get请求修改,整点黑科技
        if (config.method == 'get') {
            config.data = true
        }
        return config;
    },
    function (error) {
        // 挂掉之后怎么处理
        return Promise.reject(error);
    }
);

let errorCatch = (code, msg) => {
    code = code + "";

    //Todo: 错误码待完善
    switch (code) {
        case "1004": //接口限流，需要跳转到等待页面
            _this.$router.push('/pageWait');
            break;
        default:
            console.log(msg)
            break;
    }
};

axios.interceptors.response.use(
    function (response) {
        //浏览器级别错误直接返回
        if (response.status != 200) {
            return Promise.reject(response);
        }
        // 数据成功返回之后
        if (response.data.code != undefined && response.data.code != "1000" && response.data.code != "200") {
            errorCatch(response.data.code, response.data.message);
            return Promise.reject({
                code: response.data.code,
                msg: response.data.message,
                data: response.data.data
            });
        } else if (response.data.result != undefined && response.data.result != 1) {
            return Promise.reject({
                code: response.data.result,
                msg: response.data.message,
                data: response.data.data
            });
        }
        return response;
    },
    function (error) {
        return Promise.reject(error);
    }
);
for (const key in reqAndUrl) {
    const url = reqAndUrl[key];
    ApiService.prototype[key] = {};

    ApiService.prototype[key] = function (params = {}, options = {}) {

        const DEFAULTS = {
            method: "post",
            showLoading: false,
            timeout: 30000,
            showToast: true,
            headers: {
                'Content-Type': 'application/json',
            },
            validateStatus: false, //axios所需参数,可捕捉http 404状态码
            customRequest: false, //自定义请求
            customReponse: false, //自定义响应
        };
        let config = Object.assign({}, DEFAULTS, options);
        return axios[config.method](
            url,
            config.customRequest ? params : JSON.stringify(params),
            config
        )
            .then(res => {
                if (res && res.data) {
                    return res.data;
                } else {
                    return res;
                }
            })
            .catch(error => {
                return Promise.reject(error);
            });
    };
}

export default ApiService;